
export const authProvider = {
    async login({ username, password }) {

        const request = new Request(import.meta.env.VITE_LOGIN_API_URL, {
            method: 'POST',
            body: JSON.stringify({ 'userName': username, 'pwd': password }),
            headers: {
                'Content-Type': 'application/json;charset=UTF-8',
                'Accept': 'application/json',
            },
            //credentials: 'same-origin',
            //mode:'no-cors'
        });
        let response;
        try {
            response = await fetch(request);
        } catch (_error) {
            throw new Error('Network error');
        }
        if (response.status < 200 || response.status >= 300) {
            throw new Error(response.statusText);
        }
        const auth = await response.json();
        localStorage.setItem('auth', auth.data);
        localStorage.setItem('username', username);
    },
    async checkError(error, status) {
        //if (status === 401 || status === 403) {
        localStorage.removeItem('auth');
        localStorage.removeItem('username');
        const error_ = new Error('Session expired');
        error_.redirectTo = '/no-access';
        throw error_;
        //}
        //console.error('api error')
        // other error codes (404, 500, etc): no need to log out
    },
    async checkAuth() {
        if (!localStorage.getItem('username')) {
            throw new Error('Not authenticated');
        }
    },
    async logout() {
        const token = localStorage.getItem('auth');
        localStorage.removeItem('username');
        localStorage.removeItem('auth');

        const request = new Request(import.meta.env.VITE_BACK_SERVER_URL + import.meta.env.VITE_LOGOUT_API_URL, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json;charset=UTF-8',
                'Accept': 'application/json',
                'token': token

            },
            //credentials: 'same-origin',
            //mode:'no-cors'
        });
        let response;
        try {
            response = await fetch(request);
        } catch (_error) {
            console.info(_error)
        }
        
        
    },
    async getIdentity() {
        const username = localStorage.getItem('username');
        return { id: username, fullName: username };
    },
};